<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>顶层await</title>
</head>
<body>
    <h1>顶层await</h1>
    <h2>允许在模块的顶层使用await命令</h2>

    <script type="module">
        // 动态加载模块
        const strings = await import(`./strings.js`);
        const numbers = await import(`./numbers.js`);
        console.log(strings, numbers);

        // 异步数据加载
        const response = await fetch('https://api.example.com/data');
        const data = await response.json();
        export const result = data;

        // 条件加载
        const moduleA = (
            await import(
                condition ? './moduleA.js' : './moduleB.js'
            )
        ).default;

        // 实际应用示例
        // 配置文件加载
        const config = {
            async getConfig() {
                const response = await fetch('/config.json');
                return response.json();
            }
        };

        // 使用顶层await加载配置
        const appConfig = await config.getConfig();
        console.log('应用配置:', appConfig);

        // 资源初始化
        class DBConnection {
            static async connect() {
                return new Promise(resolve => 
                    setTimeout(() => resolve('数据库连接'), 1000)
                );
            }
        }

        // 在模块顶层等待数据库连接
        const connection = await DBConnection.connect();
        console.log('数据库状态:', connection);

        // 模块依赖处理
        async function loadDependencies() {
            const [dep1, dep2, dep3] = await Promise.all([
                import('./dep1.js'),
                import('./dep2.js'),
                import('./dep3.js')
            ]);
            return { dep1, dep2, dep3 };
        }

        // 顶层await等待所有依赖加载完成
        const dependencies = await loadDependencies();
        export { dependencies };
    </script>

    <script>
        // 注意：顶层await只能在ES模块中使用
        // 以下代码在普通脚本中会报错
        // const data = await fetch('https://api.example.com/data');
    </script>
</body>
</html> 